package org.example.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableRabbit
public class RabbitMQConfig {

    // 正常交换机和队列
    @Bean
    public DirectExchange seckillExchange() {
        return new DirectExchange("seckill.exchange");
    }

    @Bean
    public Queue seckillQueue() {
        return QueueBuilder.durable("seckill.queue").build();
    }

    @Bean
    public Binding seckillBinding() {
        return BindingBuilder.bind(seckillQueue())
                .to(seckillExchange())
                .with("seckill.timeout.routingkey");
    }

    // 死信交换机和队列(用于实现延迟消息)
    @Bean
    public DirectExchange seckillDlxExchange() {
        return new DirectExchange("seckill.dlx.exchange");
    }

    @Bean
    public Queue seckillDlxQueue() {
        return QueueBuilder.durable("seckill.dlx.queue")
                .withArgument("x-dead-letter-exchange", "seckill.exchange")
                .withArgument("x-dead-letter-routing-key", "seckill.timeout.routingkey")
                .withArgument("x-message-ttl", 60000)
                .build();
    }

    @Bean
    public Binding seckillDlxBinding() {
        return BindingBuilder.bind(seckillDlxQueue())
                .to(seckillDlxExchange())
                .with("seckill.timeout.routingkey");
    }

    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
            ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setConcurrentConsumers(3);
        factory.setMaxConcurrentConsumers(10);
        return factory;
    }
}

